/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.starter.iam.authentication.jwt;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.error.CommonErrorCode;
import com.snail.starter.commons.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author zgadmin
 * @date 2025/6/26 15:43
 */
@Slf4j
@Component
public class JwtService {

    @Value("${iam.jwt.sign:bi@sign}")
    private String sign = "bi@sign";

    public String encode(UserContext userContext) {
        checkSign();
        return JWTUtil.createToken(BeanUtil.beanToMap(userContext), sign.getBytes());
    }

    public UserContext decode(String token) {
        checkSign();
        if (null == token || "".equals(token)) {
            log.warn("token not exist:{}", token);
            return null;
        }
        boolean verify = JWTUtil.verify(token, sign.getBytes());
        if (!verify) {
            log.error("token verify error");
            throw BizException.of(CommonErrorCode.ILLEGAL_TOKEN);
        }
        UserContext userContext = JWTUtil.parseToken(token).getPayloads().toBean(UserContext.class);
        if (null != userContext) {
            userContext.setToken(token);
        }
        return userContext;
    }

    private void checkSign() {
        if ("bi@sign".equalsIgnoreCase(sign)) {
            log.warn("jwt sign is default");
        }
    }

}